from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Profile

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ['full_name', 'avatar', 'nfc_card_id']

class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer(read_only=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'is_staff', 'profile']

class RegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'password', 'email')
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        user = User.objects.create_user(
            validated_data['username'],
            email=validated_data.get('email', ''),
            password=validated_data['password']
        )
        # Profile will be automatically created by the post_save signal
        # No need to manually create it here
        return user

# ==================== 管理员专用序列化器 ====================

class AdminProfileSerializer(serializers.ModelSerializer):
    """管理员视角的用户资料序列化器，包含所有字段"""
    class Meta:
        model = Profile
        fields = ['full_name', 'avatar', 'nfc_card_id']

class AdminUserSerializer(serializers.ModelSerializer):
    """管理员视角的用户序列化器，包含详细信息"""
    profile = AdminProfileSerializer(read_only=True)
    last_login = serializers.DateTimeField(read_only=True)
    date_joined = serializers.DateTimeField(read_only=True)
    is_active = serializers.BooleanField(read_only=True)

    # 添加统计字段
    face_data_registered = serializers.SerializerMethodField()
    access_logs_count = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = [
            'id', 'username', 'email',
            'is_staff', 'is_active', 'is_superuser', 'last_login',
            'date_joined', 'profile', 'face_data_registered', 'access_logs_count'
        ]

    def get_face_data_registered(self, obj):
        """检查用户是否已注册人脸数据"""
        try:
            return hasattr(obj, 'face_data') and obj.face_data is not None
        except:
            return False

    def get_access_logs_count(self, obj):
        """获取用户访问日志数量"""
        try:
            return obj.access_logs.count()
        except:
            return 0

class AdminUserCreateSerializer(serializers.ModelSerializer):
    """管理员创建用户的序列化器"""
    password = serializers.CharField(write_only=True, min_length=6)
    confirm_password = serializers.CharField(write_only=True)

    # Profile 相关字段
    nfc_card_id = serializers.CharField(required=False, allow_blank=True)

    class Meta:
        model = User
        fields = [
            'username', 'email', 'password', 'confirm_password',
            'is_staff', 'is_active', 'is_superuser',
            'nfc_card_id'
        ]
        extra_kwargs = {
            'username': {'required': True},
            'email': {'required': True},
        }

    def validate(self, attrs):
        """验证密码确认"""
        if attrs['password'] != attrs['confirm_password']:
            raise serializers.ValidationError("密码和确认密码不匹配")
        return attrs

    def validate_nfc_card_id(self, value):
        """验证NFC卡号唯一性"""
        if value and Profile.objects.filter(nfc_card_id=value).exists():
            raise serializers.ValidationError("该NFC卡号已被使用")
        return value

    def create(self, validated_data):
        """创建用户和关联的Profile"""
        # 移除非User模型字段
        confirm_password = validated_data.pop('confirm_password')
        nfc_card_id = validated_data.pop('nfc_card_id', '')

        # 创建用户
        user = User.objects.create_user(**validated_data)

        # 更新Profile（由信号自动创建）
        if hasattr(user, 'profile'):
            profile = user.profile
            if nfc_card_id:
                profile.nfc_card_id = nfc_card_id
            profile.save()

        return user

class AdminUserUpdateSerializer(serializers.ModelSerializer):
    """管理员更新用户的序列化器"""
    # Profile 相关字段
    nfc_card_id = serializers.CharField(required=False, allow_blank=True)
    avatar = serializers.ImageField(required=False, allow_null=True)

    # 密码相关字段（可选）
    password = serializers.CharField(write_only=True, min_length=6, required=False, allow_blank=True)
    confirm_password = serializers.CharField(write_only=True, required=False, allow_blank=True)

    class Meta:
        model = User
        fields = [
            'username', 'email', 'password', 'confirm_password',
            'is_staff', 'is_active', 'is_superuser', 'nfc_card_id', 'avatar'
        ]

    def validate_nfc_card_id(self, value):
        """验证NFC卡号唯一性（排除当前用户）"""
        if value:
            existing = Profile.objects.filter(nfc_card_id=value).exclude(user=self.instance)
            if existing.exists():
                raise serializers.ValidationError("该NFC卡号已被使用")
        return value

    def validate(self, attrs):
        """验证密码确认（如果提供了密码）"""
        password = attrs.get('password')
        confirm_password = attrs.get('confirm_password')

        # 如果提供了密码，必须提供确认密码
        if password and not confirm_password:
            raise serializers.ValidationError("请确认密码")

        # 如果提供了确认密码，必须提供密码
        if confirm_password and not password:
            raise serializers.ValidationError("请输入新密码")

        # 如果都提供了，检查是否匹配
        if password and confirm_password and password != confirm_password:
            raise serializers.ValidationError("密码和确认密码不匹配")

        return attrs

    def update(self, instance, validated_data):
        """更新用户和关联的Profile"""
        # 提取Profile相关字段
        nfc_card_id = validated_data.pop('nfc_card_id', None)
        avatar = validated_data.pop('avatar', None)

        # 提取密码相关字段
        password = validated_data.pop('password', None)
        confirm_password = validated_data.pop('confirm_password', None)

        # 更新User字段
        for attr, value in validated_data.items():
            setattr(instance, attr, value)

        # 如果提供了新密码，更新密码
        if password:
            instance.set_password(password)

        instance.save()

        # 更新Profile字段
        if hasattr(instance, 'profile'):
            profile = instance.profile
            if nfc_card_id is not None:
                profile.nfc_card_id = nfc_card_id or None  # 空字符串转为None
            if avatar is not None:
                profile.avatar = avatar
            profile.save()

        return instance

class UserListFilterSerializer(serializers.Serializer):
    """用户列表过滤参数序列化器"""
    search = serializers.CharField(required=False, help_text="搜索用户名、邮箱或姓名")
    is_staff = serializers.BooleanField(required=False, help_text="过滤管理员用户")
    is_active = serializers.BooleanField(required=False, help_text="过滤活跃用户")
    has_face_data = serializers.BooleanField(required=False, help_text="过滤已注册人脸数据的用户")
    has_nfc_card = serializers.BooleanField(required=False, help_text="过滤已绑定NFC卡的用户")
    date_joined_after = serializers.DateTimeField(required=False, help_text="注册时间晚于")
    date_joined_before = serializers.DateTimeField(required=False, help_text="注册时间早于")
    ordering = serializers.CharField(required=False, help_text="排序字段")

class AdminUserBatchSerializer(serializers.Serializer):
    """批量操作用户的序列化器"""
    user_ids = serializers.ListField(
        child=serializers.IntegerField(),
        min_length=1,
        help_text="用户ID列表"
    )
    action = serializers.ChoiceField(
        choices=[
            ('activate', '激活用户'),
            ('deactivate', '停用用户'),
            ('make_staff', '设为管理员'),
            ('remove_staff', '取消管理员'),
            ('delete', '删除用户'),
        ],
        help_text="批量操作类型"
    )